#!/usr/bin/python
# -*- coding:utf-8 -*-

# 网易歌单

import requests
from lxml import etree
import os
import re
import json

path ='./那些你熟悉却又不知道名字的轻音乐'

# 确定url地址

url = 'https://music.163.com/#/playlist?id=26467411'

url = input('输入URL：')
# MP3解析URL地址
s_url = 'https://link.hhtjim.com/163/'
# 浏览器伪装头
ua = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'
}
# 动态访问
reap = requests.get(url,headers=ua).content.decode('utf-8')
# 静态访问
# f = open("demo网易云.html",'r',encoding='utf-8')
# reap = f.read()

html = re.findall('<textarea id="song-list-pre-data" style="display:none;">(.*?)</textarea>',reap)[0]
jsond = json.loads(html)   # 打印
for index in jsond:
    pic = index['album']['picUrl']  # 音乐图片
    id = index['id']  # id
    name = index['name']  # 歌名
    album = index['album']['name']  # 专辑

    # 创建MP3对象
    mp3_url = s_url + '%s'%id + '.mp3'   #音乐标题
    mp3 = requests.get(mp3_url).content

 #   import pymysql
    # mysql数据库服务器，端口：3306，而且确保服务器是处于启动状态
    # 安装pymysql：pip install pymysql
    # 建立连接
 #   conn = pymysql.connect('localhost','root','200102','mymusic',charset='utf8')
    # 建立游标
 #   cursor = conn.cursor()

    # 数据库操作
    # (1)定义一个格式化的sql语句
 #   sql = 'insert into mydbmusic(pic,music_title,name,album) values(%s,%s,%s,%s)'
    # (2)准备数据
 #   data = (pic,mp3_url,name,album)
    # (3)操作
#    try:
#       cursor.execute(sql,data)
#        conn.commit()
#    except Exception as e:
#        print('插入数据失败',e)
#        conn.rollback() #回滚

    # 关闭游标
#    cursor.close()
    # 关闭连接
#    conn.close()


    # 也可以保存到文件夹形式播放
    # 创建文件夹

    
    if not os.path.exists(path):
        os.makedirs(path)
    #
    # # 保存在文件夹里面
    with open(f'{path}/%s.mp3'%name,'wb') as file:
        file.write(mp3)
    print(f'下载完成...{name}')